package com.cloud.flowable.service.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.common.utils.ProcessQueryUtils;
import com.cloud.flowable.entity.bo.ProcessPage;
import com.cloud.flowable.entity.WfCategory;
import com.cloud.flowable.entity.WfDeployForm;
import com.cloud.flowable.entity.vo.WfDeployVo;
import com.cloud.flowable.mapper.WfCategoryMapper;
import com.cloud.flowable.mapper.WfDeployFormMapper;
import com.cloud.flowable.service.IWfDeployService;
import jakarta.annotation.Resource;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 流程部署业务逻辑层
 */
@Service
public class WfDeployServiceImpl implements IWfDeployService {

    @Resource
    private RepositoryService repositoryService;
    @Resource
    private WfDeployFormMapper deployFormMapper;
    @Resource
    private WfCategoryMapper categoryMapper;


    /**
     * 查询流程部署分页列表
     */
    @Override
    public Page<WfDeployVo> queryPageList(ProcessPage procPage) {
        Page<WfDeployVo> page = new Page<>();
        // 流程定义列表数据查询
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
                .latestVersion().orderByProcessDefinitionKey().asc();
        // 构建搜索条件
        ProcessQueryUtils.buildProcessSearch(processDefinitionQuery, procPage);
        page.setTotal(processDefinitionQuery.count());
        if (processDefinitionQuery.count() <= 0) {
            page.setRecords(new ArrayList<>());
            return page;
        }
        int offset = procPage.getPageSize() * (procPage.getPageNum() - 1);
        List<ProcessDefinition> definitionList = processDefinitionQuery.listPage(offset, procPage.getPageSize());
        List<WfDeployVo> deployVoList = new ArrayList<>(definitionList.size());
        for (ProcessDefinition processDefinition : definitionList) {
            String deploymentId = processDefinition.getDeploymentId();
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
            WfDeployVo vo = new WfDeployVo();
            vo.setDefinitionId(processDefinition.getId());
            vo.setProcessKey(processDefinition.getKey());
            vo.setProcessName(processDefinition.getName());
            vo.setVersion(processDefinition.getVersion());
            vo.setCategory(processDefinition.getCategory());
            WfCategory wfCategory = categoryMapper.getCategoryByCode(deployment.getCategory());
            vo.setCategoryName(wfCategory.getCategoryName());
            vo.setDeploymentId(processDefinition.getDeploymentId());
            vo.setSuspended(processDefinition.isSuspended());
            // 流程部署信息
            vo.setCategory(deployment.getCategory());
            vo.setDeploymentTime(deployment.getDeploymentTime());
            deployVoList.add(vo);
        }
        page.setRecords(deployVoList);
        return page;
    }

    /**
     * 查询流程部署版本列表
     */
    @Override
    public Page<WfDeployVo> queryPublishList(ProcessPage procPage) {
        Page<WfDeployVo> deployPage = new Page<>();
        // 创建查询条件
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(procPage.getProcessKey()).orderByProcessDefinitionVersion().desc();
        deployPage.setTotal(processDefinitionQuery.count());
        if (processDefinitionQuery.count() <= 0) {
            deployPage.setRecords(new ArrayList<>());
        }
        // 根据查询条件，查询所有版本
        int offset = procPage.getPageSize() * (procPage.getPageNum() - 1);
        List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(offset, procPage.getPageSize());
        List<WfDeployVo> deployVoList = processDefinitionList.stream().map(item -> {
            WfDeployVo vo = new WfDeployVo();
            vo.setDefinitionId(item.getId());
            vo.setProcessKey(item.getKey());
            vo.setProcessName(item.getName());
            vo.setVersion(item.getVersion());
            vo.setCategory(item.getCategory());
            vo.setDeploymentId(item.getDeploymentId());
            vo.setSuspended(item.isSuspended());
            return vo;
        }).collect(Collectors.toList());
        deployPage.setRecords(deployVoList);
        return deployPage;
    }

    /**
     * 激活或挂起流程
     *
     * @param state        状态
     * @param definitionId 流程定义ID
     */
    @Override
    public void updateState(String definitionId, String state) {
        if (SuspensionState.ACTIVE.toString().equals(state)) {
            // 激活
            repositoryService.activateProcessDefinitionById(definitionId, true, null);
        } else if (SuspensionState.SUSPENDED.toString().equals(state)) {
            // 挂起
            repositoryService.suspendProcessDefinitionById(definitionId, true, null);
        }
    }

    /**
     * 读取xml文件
     */
    @Override
    public String queryBpmnXmlById(String definitionId) {
        InputStream inputStream = repositoryService.getProcessModel(definitionId);
        try {
            return IoUtil.readUtf8(inputStream);
        } catch (IORuntimeException exception) {
            throw new RuntimeException("加载xml文件异常");
        }
    }

    /**
     * 删除流程模型
     */
    @Override
    @Transactional
    public void deleteByIds(List<String> deployIds) {
        for (String deployId : deployIds) {
            repositoryService.deleteDeployment(deployId, true);
            deployFormMapper.delete(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId));
        }
    }

}
